package com.oujia.cloud.cloudcommon.bean.exception;



import com.oujia.cloud.cloudcommon.api.APIResult;
import com.oujia.cloud.cloudcommon.api.APIResultEnum;
import com.oujia.cloud.cloudcommon.api.APIResultUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestControllerAdvice;

import javax.validation.ConstraintViolationException;

/**
 * 异常类捕获处理: 捕获service已知异常，controller往外抛未知异常信息
 *
 *@author  yk
 *@dateTime  2017/11/9 12:53
 *@updatetor
 */
@RestControllerAdvice
public class ServiceExceptionHandler {

	private static final Logger logger = LoggerFactory.getLogger(ServiceExceptionHandler.class);
	@ExceptionHandler(value=Exception.class)
	@ResponseBody
	public APIResult handle(Exception e) {
		logger.error(e.getMessage(), e);
		if (e instanceof ServiceException) {
			ServiceException serviceException = (ServiceException) e;
			return APIResultUtil.error(serviceException.getErrorCode(), serviceException.getMessage(),serviceException.getData());
		}
		if (e instanceof ConstraintViolationException) {
			return APIResultUtil.error(APIResultEnum.FWK_DUPLICATEKEY.getCode(),
					APIResultEnum.FWK_DUPLICATEKEY.getMsg() + ": " + e.getMessage());
		}
		if (e instanceof NullPointerException) {
			return APIResultUtil.error(APIResultEnum.POINT_FNULL.getCode(),
					APIResultEnum.POINT_FNULL.getMsg() + ": " + e.getMessage());
		}
		// 其他异常
		return APIResultUtil.error(APIResultEnum.UNKOWM_ERROR.getCode(), APIResultEnum.UNKOWM_ERROR.getMsg() + ": " + e.getMessage());
	}

}
